package st.business.tepth.business.user.busnumber.workholder.maintain.work.content.standardwork.workdetail;

import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.CustomListener;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.OnClick;
import st.business.tepth.R;
import st.business.tepth.R2;
import st.business.tepth.base.OnItemChooseListener;
import st.business.tepth.business.bean.DiagnoseBean;
import st.business.tepth.business.bean.MaintainWorkDetailBean;
import st.business.tepth.business.bean.OperationBean;
import st.business.tepth.business.bean.PartBean;
import st.business.tepth.business.bean.PartLocationBean;
import st.business.tepth.business.bean.PickGoods;
import st.business.tepth.business.bean.PickNumberBean;
import st.business.tepth.business.bean.ProgramBean;
import st.business.tepth.business.bean.post.PostMeasureValue;
import st.business.tepth.business.event.AddProgramEvent;
import st.business.tepth.business.event.GoodsEvent;
import st.business.tepth.business.goodsorder.GoodsOrderDelegate;
import st.business.tepth.business.user.busnumber.workholder.adapter.TroubleProgramAdapter;
import st.business.tepth.business.user.busnumber.workholder.dialog.DialogActionChoose;
import st.business.tepth.business.user.busnumber.workholder.dialog.DialogConfirmProgram;
import st.business.tepth.business.user.busnumber.workholder.dialog.DialogNumberSelect;
import st.business.tepth.business.user.busnumber.workholder.dialog.DialogPartChoose;
import st.business.tepth.business.user.busnumber.workholder.dialog.DialogPartLocationChoose;
import st.business.tepth.business.user.busnumber.workholder.dialog.DialogSearchTrouble;
import st.business.tepth.business.user.busnumber.workholder.repair.work.content.RepairDataConvert;
import st.business.tepth.business.user.operationchoose.OperationChooseDelegate;
import st.business.tepth.config.ItemFields;
import st.business.tepth.manager.GlobalDataManager;
import st.business.tepth.manager.UserManager;
import st.shadow.library.core.base.mvp.MvpFragment;
import st.shadow.library.core.util.utilcode.util.ScreenUtils;
import st.shadow.library.core.util.utilcode.util.ToastUtils;
import st.shadow.library.ui.dialog.DialogLoader;
import st.shadow.library.ui.dialog.IDialogClickListener;
import st.shadow.library.ui.recycler.BaseDecoration;
import st.shadow.library.ui.recycler.MultipleItemEntity;

import static st.business.tepth.business.user.busnumber.workholder.adapter.TroubleProgramAdapter.TYPE_MANUAL_UN_CONFIRM;
import static st.business.tepth.business.user.busnumber.workholder.adapter.TroubleProgramAdapter.TYPE_RELEVANCE_UN_CONFIRM;
import static st.business.tepth.business.user.busnumber.workholder.adapter.TroubleProgramAdapter.TYPE_SYSTEM_RECOMMEND_UN_CONFIRM;

/**
 * Author: shadow
 * Email:  1025431817@qq.com
 * Time:   2019-04-15 15:34
 * 保养详情
 */

public class WorkDetailDelegate extends MvpFragment<WorkDetailPresenter>
        implements WorkDetailContract.View {
    public static WorkDetailDelegate newInstance(int repairId,
                                                 int repairTaskId,
                                                 int maintainId,
                                                 String person,
                                                 int status) {
        Bundle bundle = new Bundle();
        bundle.putInt("repairId", repairId);
        bundle.putInt("status", status);
        bundle.putInt("repairTaskId", repairTaskId);
        bundle.putInt("maintainId", maintainId);
        bundle.putString("person", person);
        WorkDetailDelegate delegate = new WorkDetailDelegate();
        delegate.setArguments(bundle);
        return delegate;
    }

    @BindView(R2.id.tv_standard_work)
    TextView mTvStandardWork;
    @BindView(R2.id.tv_work_person)
    TextView mTvWorkPerson;
    @BindView(R2.id.recycler_view_diagnose)
    RecyclerView mRecyclerViewDiagnose;
    @BindView(R2.id.recycler_view_program)
    RecyclerView mRecyclerViewProgram;
    @BindView(R2.id.tv_confirm)
    TextView mTvConfirm;
    @BindView(R2.id.tv_diagnose)
    TextView mTvDiagnose;
    @BindView(R2.id.tv_add_work)
    TextView mTvAddWork;
    @BindView(R2.id.tv_commit_value)
    TextView mTvCommitValue;
    @BindView(R2.id.diver_3)
    View vDiver3;
    @BindView(R2.id.v_value)
    TextView mVvalue;
    @BindView(R2.id.recycler_view_value)
    RecyclerView mRvValue;
    private DiagnoseAdapter mDiagnoseAdapter;
    private OptionsPickerView pvCustomOptions;
    private TroubleProgramAdapter mProgramAdapter;
    private int mRepairId;
    private int mRepairTaskId;
    private int mMaintainId;
    private String mPerson;
    private int mStatus;
    private DialogLoader mDialogLoader;
    private UiDelegate mUiDelegate;
    private MaintainWorkDetailBean mMaintainWorkDetailBean;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null) {
            mRepairId = bundle.getInt("repairId");
            mRepairTaskId = bundle.getInt("repairTaskId");
            mMaintainId = bundle.getInt("maintainId");
            mPerson = bundle.getString("person");
            mStatus = bundle.getInt("status");
        }
    }

    @Override
    public WorkDetailPresenter getPresenter() {
        return new WorkDetailPresenter(this);
    }

    @Override
    public Object setLayout() {
        return R.layout.delegate_maintain_work_detail;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {
        initView();
        initData();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    private void initView() {
        mTvWorkPerson.setText(mPerson);
        mDialogLoader = new DialogLoader(_mActivity);
        mRecyclerViewDiagnose.setLayoutManager(
                new LinearLayoutManager(_mActivity, LinearLayoutManager.HORIZONTAL
                        , false));
        mRecyclerViewDiagnose.setAdapter(mDiagnoseAdapter =
                new DiagnoseAdapter(R.layout.item_maintain_diagnose, mStatus, null));
        mRecyclerViewDiagnose.addOnItemTouchListener(new OnItemChildClickListener() {
            @Override
            public void onSimpleItemChildClick(BaseQuickAdapter adapter, View view, final int position) {
                final DiagnoseBean diagnoseBean = (DiagnoseBean) adapter.getItem(position);
                if (diagnoseBean != null) {
                    if (view.getId() == R.id.iv_diagnose_delete) {
                        if (diagnoseBean.isTemp()) {
                            //本地临时的就自己删了
                            adapter.remove(position);
                            mUiDelegate.changeStateWithData();
                        } else {
                            //服务器上面的删除
                            mDialogLoader.showWarning("删除诊断", "确认删除么?",
                                    new IDialogClickListener() {
                                        @Override
                                        public void onClick() {
                                            mDialogLoader.changeToProgressType("正在删除...");
                                            mPresenter.deleteDiagnose(UserManager.getInstance().getToken(),
                                                    mRepairId, diagnoseBean.getId(), position);
                                        }
                                    });
                        }
                    } else if (view.getId() == R.id.tv_add_program) {
                        start(OperationChooseDelegate.newInstance(diagnoseBean, mRepairId
                        ));
                    }
                }

            }
        });

        initProgramView();

    }

    private void initProgramView() {
        mRecyclerViewProgram.setLayoutManager(new LinearLayoutManager(_mActivity));
        mRecyclerViewProgram.addOnItemTouchListener(new OnItemChildClickListener() {
            @Override
            public void onSimpleItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                MultipleItemEntity entity = (MultipleItemEntity) adapter.getItem(position);
                if (entity != null) {
                    int type = entity.getItemType();
                    int id = view.getId();
                    if (id == R.id.tv_action) {
                        //动作
                        chooseAction(adapter, view, position);
                    } else if (id == R.id.tv_obj || id == R.id.tv_part_code) {
                        //零部件和编码
                        choosePart(adapter, view, position, true);
                    } else if (id == R.id.tv_count) {
                        //零部件数量
                        choosePartCount(adapter, view, position);
                    } else if (id == R.id.tv_materials || id == R.id.tv_materials_code) {
                        //耗材和编码
                        choosePart(adapter, view, position, false);
                    } else if (id == R.id.tv_materials_count) {
                        //耗材数量
                        chooseGoodsCount(adapter, view, position);
                    } else if (id == R.id.tv_place) {
                        //位置
                        choosePartLocation(adapter, view, position);
                    } else if (id == R.id.tv_delete) {
                        if (type == TYPE_MANUAL_UN_CONFIRM
                                || type == TYPE_SYSTEM_RECOMMEND_UN_CONFIRM
                                || type == TYPE_RELEVANCE_UN_CONFIRM) {
                            adapter.remove(position);
                            mUiDelegate.changeStateWithData();
                        }
                    }
                }
            }
        });
        mProgramAdapter = new TroubleProgramAdapter(_mActivity, null,
                new TroubleProgramAdapter.onItemOperatorListener() {

                    @Override
                    public void onOperator(final ProgramBean program, String status, final int position) {
                        mDialogLoader.showWarning(status, "请确认",
                                new IDialogClickListener() {
                                    @Override
                                    public void onClick() {
                                        int pickStatus = program.getPicking_status();
                                        if (pickStatus >= 6 && pickStatus <= 9
                                                || pickStatus == 0) {
                                            //减去header
                                            deleteProgram(program, position - 1);
                                        } else if (pickStatus == 3 || pickStatus == 5) {
                                            //退料
                                            returnGoods(program, position - 1);
                                        }
                                    }
                                });
                    }
                }, new TroubleProgramAdapter.onItemOperatorListener() {
            @Override
            public void onOperator(ProgramBean program, String status, int position) {

            }
        }, new TroubleProgramAdapter.onItemOperatorListener() {
            @Override
            public void onOperator(ProgramBean program, String status, int position) {

            }
        });
        mProgramAdapter.addHeaderView(LayoutInflater.from(_mActivity).inflate(R.layout.item_head_work_program,
                null));
        mRecyclerViewProgram.setAdapter(mProgramAdapter);
    }

    private void initData() {
        mUiDelegate = new UiDelegate(mTvAddWork, mTvDiagnose, mRecyclerViewDiagnose,
                mDiagnoseAdapter, mRecyclerViewProgram,
                mProgramAdapter, mTvConfirm, _mActivity);
        mUiDelegate.initState(mStatus);
        //请求界面数据
        mPresenter.getDetailData(UserManager.getInstance().getToken(), mMaintainId);
        // mDialogLoader.showProgressDialog(true, "正在请求", "请稍候...");
        EventBus.getDefault().register(this);
    }

    @Override
    public void showData(MaintainWorkDetailBean workDetailBean) {
        if (workDetailBean != null) {
            mMaintainWorkDetailBean = workDetailBean;
            if (workDetailBean.getDisplayMeasured() == 0) {
                //不需要显示实测值
                mRvValue.setVisibility(View.GONE);
                mTvCommitValue.setVisibility(View.GONE);
                vDiver3.setVisibility(View.GONE);
                mVvalue.setVisibility(View.GONE);
            } else {
                mRvValue.setVisibility(View.VISIBLE);
                vDiver3.setVisibility(View.VISIBLE);
                mVvalue.setVisibility(View.VISIBLE);
                //可作业
                List<MaintainWorkDetailBean.MeasureValue>
                        valueList = workDetailBean.getMeasuredValueList();
                if (valueList != null && !valueList.isEmpty()) {
                    mRvValue.setLayoutManager(new LinearLayoutManager(_mActivity,
                            LinearLayoutManager.HORIZONTAL, false));
                    mRvValue.addItemDecoration(BaseDecoration.
                            create(Color.parseColor("#ffffff"), 5));
                    mRvValue.setAdapter(new BaseQuickAdapter<MaintainWorkDetailBean.MeasureValue,
                            BaseViewHolder>(R.layout.item_measure_value, valueList) {
                        @Override
                        protected void convert(final BaseViewHolder helper,
                                               final MaintainWorkDetailBean.MeasureValue item) {
                            helper.setText(R.id.tv_value, item.getMeasuredValue());
                            String unit = " ";
                            if (item.getUnit() != null && !"null".equals(item.getUnit())) {
                                unit = item.getUnit();
                            }
                            helper.setText(R.id.tv_unit, unit);
                            if (mStatus < 3) {
                                helper.setEnabled(R.id.view_cover, true);
                            } else {
                                helper.setEnabled(R.id.view_cover, false);
                            }
                            helper.getView(R.id.view_cover).setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    new DialogInputValue(_mActivity, new OnItemChooseListener<String>() {
                                        @Override
                                        public void onChoose(String s) {
                                            item.setMeasuredValue(s);
                                            helper.setText(R.id.tv_value, s);
                                        }
                                    }).show();
                                }
                            });

                        }
                    });
                }
                if (mStatus < 3) {
                    mTvCommitValue.setVisibility(View.VISIBLE);
                } else {
                    //不可作业
                    mTvCommitValue.setVisibility(View.GONE);
                }
            }
            mTvStandardWork.setText(workDetailBean.getStandard());
            List<DiagnoseBean> diagnoseBeans = workDetailBean.getRepairDiagnosticList();
            mDiagnoseAdapter.setNewData(diagnoseBeans);
            if (diagnoseBeans != null) {
                if (mProgramAdapter != null) {
                    mProgramAdapter.setNewData(
                            new RepairDataConvert()
                                    .programToMultipleItemEntityInMaintainDetail(diagnoseBeans, mStatus));
                }
            }
            mUiDelegate.changeStateWithData();
            if (mStatus == 3) {
                mUiDelegate.initState(mStatus);
            }
        }
    }

    @Override
    public void showError(String msg) {
        mDialogLoader.stopProgressWithFailed(msg, msg);
    }

    @Override
    public void postDiagnoseList(List<DiagnoseBean> list) {
        mDialogLoader.clearDialog();
        if (mDiagnoseAdapter != null) {
            mDiagnoseAdapter.notifyAddData(list);
            mUiDelegate.changeStateWithData();
        }
    }

    @Override
    public void deleteDiagnose(final int position) {
        mDialogLoader.stopProgressWithSuccess("删除成功", null, new IDialogClickListener() {
            @Override
            public void onClick() {
                mDialogLoader.clearDialog();
                if (mDiagnoseAdapter != null) {
                    mDiagnoseAdapter.remove(position);
                    //当没有任何诊断,不应该存在方案
                    if (mDiagnoseAdapter.getData().isEmpty()) {
                        mProgramAdapter.setNewData(null);
                    }
                    mUiDelegate.changeStateWithData();
                }
            }
        });
    }

    @Override
    public void deleteProgram(final int position) {
        mDialogLoader.stopProgressWithSuccess("删除成功", null, new IDialogClickListener() {
            @Override
            public void onClick() {
                mDialogLoader.clearDialog();
                if (mProgramAdapter != null) {
                    mProgramAdapter.remove(position);
                    mUiDelegate.changeStateWithData();
                }
            }
        });
    }

    @Subscribe(priority = 10)
    public void onAddProgramEvent(AddProgramEvent event) {
        //取消事件传递
        EventBus.getDefault().cancelEventDelivery(event);
        if (event.mRepairId == mRepairId) {
            mProgramAdapter.addData(0, event.mItemEntity);
            mUiDelegate.changeStateWithData();
        }
    }

    @OnClick({R2.id.tv_back})
    public void onBack() {
        pop();
    }

    @OnClick(R2.id.tv_add_work)
    public void onAddDiagnose() {
        new DialogSearchTrouble(_mActivity, mRepairId, mRepairTaskId
                , 0, UserManager.getInstance().getToken(),
                new OnItemChooseListener<DiagnoseBean>() {
                    @Override
                    public void onChoose(DiagnoseBean diagnoseBean) {
                        mDiagnoseAdapter.addTempData(diagnoseBean);
                        mUiDelegate.changeStateWithData();
                    }
                }).adjustSize();
    }


    @OnClick(R2.id.tv_confirm)
    public void onConfirm() {
        if (mUiDelegate != null) {
            switch (mUiDelegate.getSTATE()) {
                case CONFIRM_DIAGNOSE:
                    commitDiagnose();
                    break;
                case CONFIRM_PROGRAM:
                    commitProgram();
                    break;
            }
        }
    }

    private void commitDiagnose() {
        mDialogLoader.showProgressDialog(false, "正在提交",
                "请稍候...");
        mPresenter.confirmDiagnoseList(UserManager.getInstance().getToken(),
                mRepairId, mRepairTaskId, mMaintainId,
                JSON.toJSONString(mDiagnoseAdapter.getTempList()));
    }

    private void commitProgram() {
        if (!mProgramAdapter.getData().isEmpty()) {
            mPresenter.confirmProgram(UserManager.getInstance().getToken(),
                    mRepairId, mRepairTaskId, mMaintainId,
                    new RepairDataConvert().programListToJson(mProgramAdapter.getData(),
                            mRepairId,
                            0, 2));
            mDialogLoader.showProgressDialog(false, "正在提交", "请稍候...");
        } else {
            ToastUtils.showShort("请先添加方案");
        }
    }

    /**
     * 选择动作
     */
    private void chooseAction(final BaseQuickAdapter adapter, final View view, final int position) {
        new DialogActionChoose(_mActivity, GlobalDataManager.getInstance().getOperationBeans(),
                new OnItemChooseListener<OperationBean>() {

                    @Override
                    public void onChoose(OperationBean operationBean) {
                        Log.e("onChoose", position + "");
                        MultipleItemEntity entity = (MultipleItemEntity) adapter.getItem(position);
                        if (entity != null) {
                            ProgramBean diagnoseBean = entity.getField(ItemFields.ITEM_OBJ);
                            diagnoseBean.setAction_name(operationBean.getAction_name());
                            diagnoseBean.setMaintenance_action_id(operationBean.getId());
                            ((TextView) view).setText(operationBean.getAction_name());
//                            adapter.notifyItemChanged(position);
                        }
                    }
                }).show();
    }

    /**
     * 选择零部件和编码
     */
    private void choosePart(final BaseQuickAdapter adapter, final View view, final int position,
                            final boolean isPart) {
        DialogPartChoose dialogPartChoose = new DialogPartChoose(_mActivity, mRepairId,
                new OnItemChooseListener<PartBean>() {
                    @Override
                    public void onChoose(PartBean partBean) {
                        MultipleItemEntity entity = (MultipleItemEntity) adapter.getItem(position);
                        if (entity != null) {
                            ProgramBean diagnoseBean = entity.getField(ItemFields.ITEM_OBJ);
                            TextView tv = ((TextView) view);
                            if (isPart) {
                                diagnoseBean.setPart(partBean);
                                if (view.getId() == R.id.tv_obj) {
                                    //零件
                                    tv.setText(partBean.getMaterial_name());
                                    TextView tvCode = (TextView) adapter.getViewByPosition(mRecyclerViewProgram,
                                            position + 1, R.id.tv_part_code);
                                    if (tvCode != null) {
                                        tvCode.setText(partBean.getMaterial_no());
                                    }
                                } else {
                                    //编号
                                    tv.setText(partBean.getMaterial_no());
                                    TextView tvName = (TextView) adapter.getViewByPosition(mRecyclerViewProgram,
                                            position + 1, R.id.tv_obj);
                                    if (tvName != null) {
                                        tvName.setText(partBean.getMaterial_name());
                                    }
                                }
                                TextView tvUnit = (TextView) adapter.getViewByPosition(mRecyclerViewProgram,
                                        position + 1, R.id.tv_unit);
                                if (tvUnit != null) {
                                    tvUnit.setText(partBean.getUnit() == null ? "无" : partBean.getUnit());
                                }
                            } else {
                                diagnoseBean.setMaterial(partBean);
                                if (view.getId() == R.id.tv_materials) {
                                    //耗材
                                    tv.setText(partBean.getMaterial_name());
                                    TextView tvCode = (TextView) adapter.getViewByPosition(mRecyclerViewProgram,
                                            position + 1, R.id.tv_materials_code);
                                    if (tvCode != null) {
                                        tvCode.setText(partBean.getMaterial_no());
                                    }
                                } else {
                                    //编号
                                    tv.setText(partBean.getMaterial_no());
                                    TextView tvName = (TextView) adapter.getViewByPosition(mRecyclerViewProgram,
                                            position + 1, R.id.tv_materials);
                                    if (tvName != null) {
                                        tvName.setText(partBean.getMaterial_name());
                                    }
                                }
                            }
                        }
                    }
                }, isPart);
        Window dialogWindow = dialogPartChoose.getWindow();
        if (dialogWindow != null) {
            WindowManager.LayoutParams lp = dialogWindow.getAttributes();
            lp.width = ScreenUtils.getScreenWidth() * 1000 / 1280; // 宽度
            lp.height = ScreenUtils.getScreenHeight() * 720 / 1024; // 高度
            dialogWindow.setGravity(Gravity.CENTER);
            dialogWindow.setAttributes(lp);
            dialogPartChoose.show();
        }
    }

    /**
     * 零部件输入选择
     */
    private void choosePartCount(final BaseQuickAdapter adapter, final View view, final int position) {
        pvCustomOptions = new OptionsPickerBuilder(_mActivity,
                new OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int option2, int options3, View v) {
                        //返回的分别是三个级别的选中位置
                        MultipleItemEntity entity = (MultipleItemEntity) adapter.getItem(position);
                        if (entity != null) {
                            ProgramBean programBean = entity.getField(ItemFields.ITEM_OBJ);
                            if (programBean != null) {
                                PartBean partBean = programBean.getPart();
                                if (partBean != null) {
                                    partBean.setVal(options1 + 1);
                                    ((TextView) view).setText(String.format(
                                            Locale.CHINA, "%d", options1 + 1));
                                }
                            }
                        }
                    }
                })
                .setLayoutRes(R.layout.dialog_number_select, new CustomListener() {
                    @Override
                    public void customLayout(View v) {
                        v.findViewById(R.id.iv_close).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvCustomOptions.dismiss();
                            }
                        });
                        v.findViewById(R.id.tv_confirm).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvCustomOptions.returnData();
                                pvCustomOptions.dismiss();
                            }
                        });
                    }
                })
                .isDialog(true)
                .setOutSideCancelable(false)
                .build();
        List<PickNumberBean> list = new ArrayList<>();
        for (int i = 1; i < 50; i++) {
            list.add(new PickNumberBean(i + ""));
        }
        //noinspection unchecked
        pvCustomOptions.setPicker(list);//添加数据
        pvCustomOptions.show();
    }

    /**
     * 耗材数量选择
     */
    private void chooseGoodsCount(BaseQuickAdapter adapter, final View view, int position) {
        MultipleItemEntity entity = (MultipleItemEntity) adapter.getItem(position);
        if (entity != null) {
            ProgramBean diagnoseBean = entity.getField(ItemFields.ITEM_OBJ);
            final PartBean partBean = diagnoseBean.getMaterial();
            if (partBean == null) {
                ToastUtils.showShort("请先选择耗材");
            } else {
                DialogNumberSelect dialogGoodsCount = new DialogNumberSelect(_mActivity,
                        new OnItemChooseListener<String>() {
                            @Override
                            public void onChoose(String s) {
                                partBean.setVal(Integer.parseInt(s));
                                ((TextView) view).setText(String.format("%s%s", s, partBean.getUnit() == null ? "L" :
                                        partBean.getUnit()));
                            }
                        });
                Window dialogWindow = dialogGoodsCount.getWindow();
                if (dialogWindow != null) {
                    WindowManager.LayoutParams lp = dialogWindow.getAttributes();
                    lp.width = ScreenUtils.getScreenWidth() * 1000 / 1280; // 宽度
                    lp.height = ScreenUtils.getScreenHeight() * 420 / 1024; // 高度
                    dialogWindow.setGravity(Gravity.CENTER);
                    dialogWindow.setAttributes(lp);
                    dialogGoodsCount.show();
                }
            }
        }
    }

    /**
     * 位置选择
     *
     * @param adapter
     * @param view
     * @param position
     */
    private void choosePartLocation(final BaseQuickAdapter adapter, final View view, final int position) {
        new DialogPartLocationChoose(_mActivity,
                new DialogPartLocationChoose.OnLocationChooseListener() {

                    @Override
                    public void onChoose(PartLocationBean partLocationBean, String temp) {
                        if (temp.isEmpty()) {
                            //没有临时添加的位置
                            MultipleItemEntity entity = (MultipleItemEntity) adapter.getItem(position);
                            if (entity != null) {
                                ProgramBean programBean = entity.getField(ItemFields.ITEM_OBJ);
                                programBean.setPositionName(partLocationBean.getPositionName());
                                programBean.setPositionCode(partLocationBean.getPositionCode());
                                //diagnoseBean.setAction_name(operationBean.getAction_name());
                                // diagnoseBean.setMaintenance_action_id(operationBean.getId());
                                ((TextView) view).setText(partLocationBean.getPositionName());
                            }
                        } else {
                            //有临时添加的位置
                            mDialogLoader.showProgressDialog(false, "正在添加",
                                    "请稍候...");
                            mPresenter.addTempLocation(UserManager.getInstance().getToken(),
                                    position, partLocationBean, temp);

                        }

                    }
                }).measureSize().show();
    }

    /**
     * 删除方案
     */
    private void deleteProgram(final ProgramBean programBean, final int position) {
//        DialogDeleteProgram dialogDeleteProgram = new DialogDeleteProgram(_mActivity,
//                programBean,
//                new OnItemChooseListener<Object>() {
//                    @Override
//                    public void onChoose(Object o) {
        mDialogLoader.changeToProgressType("正在提交...");
        mPresenter.deleteProgram(UserManager.getInstance().getToken(),
                mRepairId, programBean.getFault_diagnostic_id(),
                programBean.getId(), position);
//                    }
//                });
//        Window dialogWindow = dialogDeleteProgram.getWindow();
//        if (dialogWindow != null) {
//            WindowManager.LayoutParams lp = dialogWindow.getAttributes();
//            lp.width = ScreenUtils.getScreenWidth() * 1000 / 1280; // 宽度
//            lp.height = ScreenUtils.getScreenHeight() * 820 / 1024; // 高度
//            dialogWindow.setGravity(Gravity.CENTER);
//            dialogWindow.setAttributes(lp);
//            dialogDeleteProgram.show();
//        }
    }

    /**
     * 退料
     */
    public void returnGoods(final ProgramBean programBean, final int position) {
        mDialogLoader.changeToProgressType("正在提交...");
        mPresenter.returnGoods(UserManager.getInstance().getToken(),
                "", programBean.getId(), position);
    }

    @Override
    public void returnGoodsSucceed(int position) {
        mDialogLoader.stopProgressWithSuccess("退料成功", null, new IDialogClickListener() {
            @Override
            public void onClick() {
                mDialogLoader.clearDialog();
            }
        });
        if (mProgramAdapter != null) {
            MultipleItemEntity entity = mProgramAdapter.getItem(position);
            if (entity != null) {
                ProgramBean programBean = entity.getField(ItemFields.ITEM_OBJ);
                if (programBean != null) {
                    //退料中
                    programBean.setPicking_status(6);
                    mProgramAdapter.notifyItemChanged(position + 1);
                }
            }
        }
    }

    @Override
    public void showPickGoods(final List<PickGoods> list) {
        _mActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (list != null && !list.isEmpty()) {
                    mDialogLoader.clearDialog();
                    DialogConfirmProgram dialogDeleteProgram = new DialogConfirmProgram(_mActivity,
                            list,
                            new OnItemChooseListener<String>() {
                                @Override
                                public void onChoose(String o) {
                                    //发起领料
                                    mDialogLoader.showProgressDialog(true,
                                            "正在提交", "请稍候...");
                                    mPresenter.pickGoods(UserManager.getInstance().getToken(), mMaintainId,
                                            o);
                                }
                            });
                    Window dialogWindow = dialogDeleteProgram.getWindow();
                    if (dialogWindow != null) {
                        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
                        lp.width = ScreenUtils.getScreenWidth() * 1000 / 1280; // 宽度
                        lp.height = ScreenUtils.getScreenHeight() * 820 / 1024; // 高度
                        dialogWindow.setGravity(Gravity.CENTER);
                        dialogWindow.setAttributes(lp);
                        dialogDeleteProgram.show();
                    }
                } else {
                    mDialogLoader.stopProgressWithSuccess("方案提交成功", null,
                            new IDialogClickListener() {
                                @Override
                                public void onClick() {
                                    mDialogLoader.clearDialog();
                                }
                            });
                }
            }
        });

    }

    @Override
    public void pickGoodsSucceed() {
        _mActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mDialogLoader.stopProgressWithSuccess("申请已提交",
                        "可在[我的领料单]中查看审批进度",
                        new IDialogClickListener() {
                            @Override
                            public void onClick() {
                                mDialogLoader.clearDialog();
                                start(GoodsOrderDelegate.newInstance(mRepairId));
                            }
                        });
                mDialogLoader.setConfirmText("查看我的领料单");
                mDialogLoader.showCancel(true);
            }
        });
    }

    @Override
    public void commitValueSucceed() {
        mDialogLoader.stopProgressWithSuccess("提交成功", null, new IDialogClickListener() {
            @Override
            public void onClick() {
                mDialogLoader.clearDialog();
            }
        });
    }

    @Override
    public void showTempLocation(PartLocationBean partLocationBean, int position) {
        mDialogLoader.clearDialog();
        MultipleItemEntity entity = mProgramAdapter.getItem(position);
        if (entity != null) {
            ProgramBean programBean = entity.getField(ItemFields.ITEM_OBJ);
            programBean.setPositionName(partLocationBean.getPositionName());
            programBean.setPositionCode(partLocationBean.getPositionCode());
            mProgramAdapter.notifyItemChanged(position + 1);
        }
    }

    @Subscribe
    public void onGoodsEvent(GoodsEvent event) {
        mPresenter.getDetailData(UserManager.getInstance().getToken(), mMaintainId);
    }

    @OnClick(R2.id.tv_commit_value)
    public void onCommitValue() {
        if (mMaintainWorkDetailBean != null) {
            List<MaintainWorkDetailBean.MeasureValue> valueList =
                    mMaintainWorkDetailBean.getMeasuredValueList();
            if (valueList != null && !valueList.isEmpty()) {
                PostMeasureValue measureValue = new PostMeasureValue();
                measureValue.setMaintenanceId(mMaintainId);
                measureValue.setMeasuredValueList(valueList);
                mPresenter.commitMeasureValue(UserManager.getInstance().getToken(),
                        mMaintainId, JSON.toJSONString(measureValue));
                mDialogLoader.showProgressDialog(true, "正在提交",
                        "请稍候...");
            }
        }
    }
}